<?php

class BorrowsAction extends BaseAction{

	public function index(){
		//搜索


		if (!empty($_GET['keyword'])) {
			if ($_GET['searchtype'] == 'UID') {
				$condition['uid'] = $_GET['keyword'];
			}else if ($_GET['searchtype'] == 'DID') {
				$condition['did'] = array('like', '%' . $_GET['keyword'] . '%');
			}
		}

		$Db_borrows       = D('Borrows');
		//'投标进度/状态（0. 默认 1.正在投标 2.等待还款 3.还款结束 4.已过期 5.等待审核）',
		$order_list_count = $Db_borrows->where($condition)->count();
		import('@.ORG.system_page');
		$p = new Page($order_list_count, 15);
		$order_list = $Db_borrows->field(true)->order('`addTime` DESC')->where($condition)->limit($p->firstRow . ',' .$p->listRows)->select();
//		//获取真实姓名
//		if($order_list){
//			$Db_user = D('User');
//			foreach($order_list as &$val){
//				$val['nickname'] = $Db_user->where('`uid` = '.$val['uid'])->getField('`nickname`');
//			}
//		}
		$this->assign('order_list',$order_list);
		$pagebar = $p->show();
		$this->assign('pagebar', $pagebar);
		$this->display();
	}

	public function borrow_edit(){
		$condition['bid'] = intval($_GET['bid']);
		$Db_borrows       = D('Borrows');
		$now_order = $Db_borrows->field(true)->where($condition)->find();
		if(empty($now_order)){
			$this->frame_error_tips('数据库中没有查询到该内容！',3);
		}
		//if($now_order['repayDate'] == "0000-00-00") $now_order['repayDate'] = '';
		$this->assign('now_order',$now_order);

		$this->display();
	}

	public function borrow_edit_save(){

		// 后台审核通过之后确认授信
		$Db_borrows       = D('Borrows');
		$condition['bid'] = intval($_POST['bid']);
		$now_order = $Db_borrows->field(true)->where($condition)->find();
		//通过审核无需操作该项
		//dump($_POST);die;
		$_POST['status'] = intval($_POST['status']);
		//$_POST['repayDate'] = trim($_POST['repayDate']);
		$Db_pledges = 	D('Pledges');
		$Db_pledge_domain = D('Pledge_domain');
		if($_POST['status'] == 7){
			//拒绝审核则要减去借款总额，增加可用信额
			$Db_pledges->where('`uid`='.$now_order['uid'])->setDec('brrowing_total',$now_order['Amount']);//减去 借款总额
			$Db_pledges->where('`uid`='.$now_order['uid'])->setInc('credit_now',    $now_order['Amount']);//增加 可用信额
			//$borrows_pids = $Db_borrows->where(array('bid'=>$bid))->getField('pids');
			$pledge_ids = explode(',',$now_order['pids']);
			foreach($pledge_ids as $val){
				$pledge_domain_save['rz_status'] = 0;
				$Db_pledge_domain->where('`pid`='.$val)->data($pledge_domain_save)->save();
			}
			$Db_borrows->data($_POST)->save();
			$_POST['status'] = 7;
			$this->frame_submit_tips(1,'已经拒绝成功！');exit;

		}

//		if($_POST['status'] == 1){
//			//$_POST['repayDate'] = $now_order['ExpiredAt'];//借款利息是从借款列表满标的第当天开始计算。
//			if( $_POST['repayDate'] == "0000-00-00" || empty($_POST['repayDate'])){
//				$this->frame_error_tips('审核通过，必须设置一个还款日期！',3);
//			}
//
//			if(strtotime($now_order['ExpiredAt']) >= strtotime($_POST['repayDate'])){
//				$this->frame_error_tips('审核通过，还款日期必须要大于满标日期！',3);
//			}
//		}

		$_POST['needAmount'] = $now_order['Amount'];
		$_POST['fabiaoTime'] = time(); //发标时间（审核通过即代表发布贷款）
		$today = date('Y-m-d',time());
		$Db_automatic = D('Automatic'); //自动投标
		/******************************************************************/


		/**********************************************************************/

		if($Db_borrows->data($_POST)->save()){ //审核成功
			//borrow_total 共发布贷款数
			$Db_pledges->where('`uid`='.$now_order['uid'])->setInc('borrow_total');//增加 共发布贷款数

			/**
			 *
			自动投标规则说明
			5、若按照您设置的自动投标配置，系统为您成功投完所设置的金额后，该自动投标配置自动转为失效配置；
			6、当一个借入列表满足多个设置自动投标的用户时，系统优先选择最低利率设置最低的用户完成投标；如设置的最低利率相同，系统则优先选择提交时间最早的用户完成投标；
			*/
			//$get_automatics_con['autotype'] = 1;
			$get_automatics_con['invalid'] = 1;
			$get_automatics_con['MinRate'] = array('elt',$now_order['Rate']); //贷款的利率至少要大于或者等于投资设置的利率

			//判断是不是符合该用户的投资期数（天/月）
			if(intval($now_order['LoanCycleDay']) > 0){ //天
				$get_automatics_con['LoanCycleDay'] = array('like',"%{$now_order['LoanCycleDay']}%");
			}else if(intval($now_order['LoanCycleMonth']) > 0){ //月
				$get_automatics_con['LoanCycleMonth'] = array('like',"%{$now_order['LoanCycleMonth']}%");
			}
			$get_automatics_con['uid'] = array('neq',$now_order['borrowstatus']); //排除自己投资自己
			//echo "借款信息：<br/>";
			//dump($now_order);
			//按照利率最低排序，再添加时间最早来升序排序 ,还要排除自己投资自己
			$get_automatics = $Db_automatic->where($get_automatics_con)->order('`MinRate` ASC ,`addTime` ASC')->find();
			/*echo $Db_automatic->getLastSql();
			echo "<br/>自动投标信息：";
			dump($get_automatics);*/
			//$rate = array();
			if(!empty($get_automatics)){
				/**
				 * 【自动投标和回款投标】 开始
				 */
				$Db_user = D('User');
				$Db_pledges = D('Pledges');
				$Db_investment = D('Investment');//入 投资人

				$investmentdata['uid']      = $get_automatics['uid'];
				$investmentdata['iname']    = $Db_user->where('`uid`='.$get_automatics['uid'])->getField('nickname');
				$investmentdata['did']      = $now_order['bid'];
				$investmentdata['itime']    = time();
				//年利率转换为小数
				$automatics_save_data['Rate'] = $now_order['Rate']; //自动投标真正的年利率
				$now_order['Rate'] = number_format($now_order['Rate'] / 100,4);

				//还款周期，如果是月的全部转换为 天
				if($now_order['LoanCycleDay'] != 0 || !empty($now_order['LoanCycleDay'])){
					$now_order['LoanCycle'] = $now_order['LoanCycleDay'];
					$total_days = $now_order['LoanCycleDay'];
				}else{
					//每个月按照30天来计算
					$now_order['LoanCycle'] = $now_order['LoanCycleMonth'] * 30;
					$total_days = $now_order['LoanCycleMonth'] * 30;
				}

//	        $now_order['Rate'] = '0.1500';
//	        $now_order['LoanCycle'] = 15;
//	        echo "借入利率：".$now_order['Rate'] ;
				$investmentdata['Rate']     = $now_order['Rate']; //投资贷款的年利率
				$investmentdata['LoanCycle']= $now_order['LoanCycle']; //还款周期
				//检查该用户的余额是否大于或者等于本次贷款的总贷款额
				$user_now_money =  $Db_user->where('`uid`='.$get_automatics['uid'])->getField('now_money');
				// 剩余-50000 = 一共100000 - 需要150000  客户保留50000  直接跳走
				// 剩余50000  = 一共100000 - 需要50000  客户保留40000
				$can_use_money = $user_now_money - $now_order['Amount'];
				if($get_automatics['is_open'] == 1 && ($can_use_money >= $get_automatics['reserved_meoney'])){ //回款自动投资
					/**  【回款续投】 开始
					 * 功能开启：按照投资人要求保留一定的金额后按客户设置的利率将回款后的资金投出，一旦投资满标资金将无法撤回！
					功能关闭：需要投资人手动关闭，关闭后结束回款续投功能。
					特别说明：回款续投金额=下次回款金额+账户余额-保留金额。
					 */
					//  echo '该用户的现在有资金：'.$user_now_money."<br/>";
					//  echo "减去投资{$now_order['Amount']}剩余的资金({$can_use_money})是否还大于或者等于保留资金({$get_automatics['reserved_meoney']})：".(($can_use_money > $get_automatics['reserved_meoney']) ? "大于":"小于") ."<br/>";
					//按照投资人要求保留一定的金额后按客户设置的利率将回款后的资金投出，一旦投资满标资金将无法撤回！
					// 贷款总额 50000   账号可以投资余额 100000   投资应该是 50000 扣除资金应该 50000
					$investmentdata['Amount']       = $now_order['Amount'];
					$borrows_save_data['needAmount'] = 0;// 直接是 0 一次性投满
					$borrows_save_data['status'] = 2; //投资已经完成 100%的进度,投资人等待还款阶段,发布人开始计算 待还总额
					$investmentdata['itime']    = time();
					//每期利息收益 = 年利率 * 投资额 / 360 * 还款周期
					$investmentdata['nsy']      = number_format($now_order['Rate'] * $now_order['Amount'] / 360 * $now_order['LoanCycle'],2);; //每期利息收益
					$investmentdata['LoanCycle']= $now_order['LoanCycle'];
					$investmentdata['Amountdx'] = $this->number2Chinese($now_order['Amount']);
					$investmentdata['status']   = 2; //满标可以直接修改为收款

					$pledgesresult =  $Db_pledges->where('`uid`='.$get_automatics['uid'])->find();
					if(!empty($pledgesresult)){
						$Db_pledges->where('`uid`='.$get_automatics['uid'])->setInc('lend_total',$now_order['Amount']); //增加个人借出总额,
					}else{
						$pledges_add['uid'] =$get_automatics['uid'];
						$pledges_add['lend_total'] = $now_order['Amount'];
						$Db_pledges->add($pledges_add);
					}

					// 投标人的资金记录，结金额记录 【投标xxxx 冻结资金】
					$Db_user_money_list = M('User_money_list');
					$money_list_data['desc']       = "【自动】投标 [{$now_order['did']}] 借出扣款";
					$money_list_data['type']       = 22; //借出扣款
					$money_list_data['typeofs']    = 1;
					$money_list_data['time']       = time();
					$money_list_data['uid']        = $get_automatics['uid'];
					$money_list_data['money']      = $now_order['Amount'];
					$money_list_data['now_money']  = $user_now_money -  $now_order['Amount'];
					$Db_user_money_list->add($money_list_data);

					//满标不可以撤回资金
/*
					$Db_user_freeze = D('User_freeze');
					$user_freeze_data['info']       = "【自动】投标 [{$now_order['did']}] 冻结资金";
					$user_freeze_data['type']       = 7; // 7 投标成功资金冻结
					$user_freeze_data['freezetime'] = time();
					$user_freeze_data['uid']        = $get_automatics['uid'];
					$user_freeze_data['freezemoney']= $now_order['Amount'];
					$user_freeze_data['status']     = 0;
					$user_freeze_data['typeofs']    = 1;
					$Db_user_freeze->add($user_freeze_data);

*/

					/**
					 * `repayDate` date NOT NULL COMMENT '第一次应还时间： 满标时间 + 借款周期周期',
					`FullScaleTime` date NOT NULL COMMENT '满标时间',
					`NextRepayDate` date NOT NULL COMMENT '下一次还款时间||第一次应还时间： 满标时间 + 借款周期周期',',
					`contractExpire` date NOT NULL COMMENT '合同到期时间'= 第一次还款时间 + 借款周期 ,
					 */

					$Db_user->where('`uid`='.$get_automatics['uid'])->setDec('now_money',$now_order['Amount']);//减去用户金额，减去还需要投资金额
					$borrows_save_data['investor_tatol'] = $now_order['investor_tatol'] + 1;	//总投资数
					$borrows_save_data['inves_uids']     =   $get_automatics['uid'];//投资人uid
					$borrows_save_data['bid'] = $now_order['bid'];
					$borrows_save_data['invesing'] = 100;//投资进度(投资总额-需要投资金额/投资总额)

					$borrows_save_data['FullScaleTime'] = $today; //满标时间
					$borrows_save_data['NextRepayDate'] =  date('Y-m-d',strtotime("$today  + $total_days day"));
					$borrows_save_data['contractExpire'] =  date('Y-m-d',strtotime("{$borrows_save_data['NextRepayDate']}  + $total_days day"));
					$Db_borrows->data($borrows_save_data)->save(); //更新借款信息
					$Db_investment->data($investmentdata)->add(); //添加投资人信息
					//贷款人增加贷款总额
					$stay_total = $now_order['Amount'] + $now_order['zlx'] + $now_order['zglf']; //待还总额 = 本次借款总额+本次总利息 + 管理费
					$Db_pledges->where(array('uid'=>$now_order['borrowstatus']))->setInc('stay_total',$stay_total);

//					file_put_contents('is_open_borrows_save_data.log',print_r($borrows_save_data,true));
//					file_put_contents('is_open_investmentdata.log',print_r($investmentdata,true));
					/**
					echo "更新借款信息<br/>";
					dump($borrows_save_data);
					echo "添加投资人信息<br/>";
					dump($investmentdata);
					 */
					/**  【回款续投】 结束*/
				}else{
					/** 【自动投标】 开始   投标总额 在设置自动投标的时候已经扣除过 now_menory ，
					 * 如有投资还有剩余只需要加入now_menory即可，满标
					 * 如果投资刚好等于设置的投标总额，则不需要理会，满标
					 * 如果筹资的款额大于设置的投标总额，则设置的投标总额全部投注，这需要冻结资金，因为如果未满标则退回
					 * */
					$pledgesresult =  $Db_pledges->where('`uid`='.$get_automatics['uid'])->find();

					//是否有剩余  = 自动投标总额 - 借款总额
					$surplus_meoney = $get_automatics['total_amount'] - $now_order['Amount'];
					if($surplus_meoney < 0){ //贷款总额 》 投标总额， 已投资金额 = 投标总额，
						$investmentdata['status']   = 1; //投资中
						$investmentdata['Amount']   = $get_automatics['total_amount'];
						$investmentdata['Amountdx'] = $this->number2Chinese($get_automatics['total_amount']); //投资中文数字
						//每期利息收益 = 年利率 * 投资额 / 360 * 还款周期
						$investmentdata['nsy'] =number_format($now_order['Rate'] * $get_automatics['total_amount'] / 360 * $now_order['LoanCycle'],2);; //每期利息收益
						$borrows_save_data['status'] = 1;//借款还在集标中
						$borrows_save_data['needAmount'] = $now_order['needAmount'] - $get_automatics['total_amount'];//先减去还需要投资金额
						$automatics_save_data['has_meoney']     = $get_automatics['total_amount']; //已经投资金额
						$automatics_save_data['surplus_meoney'] =0; //投资资金剩余为 0
						//贷款人增加贷款总额
						$stay_total = $get_automatics['total_amount'] + $now_order['zlx'] + $now_order['zglf']; //待还总额 = 本次借款总额+本次总利息 + 管理费
						$Db_pledges->where(array('uid'=>$now_order['borrowstatus']))->setInc('stay_total',$stay_total);
						if(!empty($pledgesresult)){
							$Db_pledges->where('`uid`='.$get_automatics['uid'])->setInc('lend_total',$get_automatics['total_amount']); //增加个人借出总额,
						}else{
							$pledges_add['uid'] =$get_automatics['uid'];
							$pledges_add['lend_total'] = $get_automatics['Amount'];
							$Db_pledges->add($pledges_add);
						}

						// 投标人的资金记录，结金额记录 【投标xxxx 冻结资金】

						$Db_user_money_list = M('User_money_list');
						$money_list_data['desc']       = "【自动】投标 [{$now_order['did']}] 借出扣款";
						$money_list_data['type']       = 22; //借出扣款
						$money_list_data['typeofs']    = 1;
						$money_list_data['time']       = time();
						$money_list_data['uid']        = $get_automatics['uid'];
						$money_list_data['money']      = $get_automatics['total_amount'];
						$money_list_data['now_money']  = $user_now_money -  $get_automatics['total_amount'];
						$Db_user_money_list->add($money_list_data);

						$Db_user_freeze = D('User_freeze');
						$user_freeze_data['info']       = "【自动】投标 [{$now_order['did']}] 冻结资金";
						$user_freeze_data['type']       = 7; // 7 投标成功资金冻结
						$user_freeze_data['freezetime'] = time();
						$user_freeze_data['uid']        = $get_automatics['uid'];
						$user_freeze_data['freezemoney']= $get_automatics['total_amount'];
						$user_freeze_data['status']     = 0;
						$user_freeze_data['typeofs']    = 1;
						$Db_user_freeze->add($user_freeze_data);




					}else if($surplus_meoney  == 0){ //已投资金额 = 投标总额，剩余资金为 0 ，满标

						$investmentdata['status']   = 2; //满标可以直接修改为收款
						$investmentdata['Amount']   = $get_automatics['total_amount'];
						$investmentdata['Amountdx'] = $this->number2Chinese($get_automatics['total_amount']); //投资中文数字
						//每期利息收益 = 年利率 * 投资额 / 360 * 还款周期
						$investmentdata['nsy'] =number_format($now_order['Rate'] * $get_automatics['total_amount'] / 360 * $now_order['LoanCycle'],2);; //每期利息收益
						$borrows_save_data['status'] = 2; //投资已经完成 100%的进度,投资人等待还款阶段,发布人开始计算 待还总额
						//贷款人增加贷款总额
						$stay_total = $now_order['Amount'] + $now_order['zlx'] + $now_order['zglf']; //待还总额 = 本次借款总额+本次总利息 + 管理费
						$Db_pledges->where(array('uid'=>$now_order['borrowstatus']))->setInc('stay_total',$stay_total);
						$borrows_save_data['needAmount'] = $now_order['needAmount'] - $get_automatics['total_amount'];//先减去还需要投资金额
						$borrows_save_data['FullScaleTime'] = $today; //满标时间
						$borrows_save_data['NextRepayDate'] =  date('Y-m-d',strtotime("$today  + $total_days day"));
						$borrows_save_data['contractExpire'] =  date('Y-m-d',strtotime("{$borrows_save_data['NextRepayDate']}  + $total_days day"));
						$automatics_save_data['has_meoney']     = $get_automatics['total_amount']; //已经投资金额
						$automatics_save_data['surplus_meoney'] =$surplus_meoney;
						if(!empty($pledgesresult)){
							$Db_pledges->where('`uid`='.$get_automatics['uid'])->setInc('lend_total',$get_automatics['total_amount']); //增加个人借出总额,
						}else{
							$pledges_add['uid'] =$get_automatics['uid'];
							$pledges_add['lend_total'] = $get_automatics['Amount'];
							$Db_pledges->add($pledges_add);
						}

						// 投标人的资金记录，结金额记录 【投标xxxx 冻结资金】

						$Db_user_money_list = M('User_money_list');

						$money_list_data['desc']       = "【自动】投标 [{$now_order['did']}] 借出扣款";
						$money_list_data['type']       = 22; //借出扣款
						$money_list_data['typeofs']    = 1;
						$money_list_data['time']       = time();
						$money_list_data['uid']        = $get_automatics['uid'];
						$money_list_data['money']      = $get_automatics['total_amount'];
						$money_list_data['now_money']  = $user_now_money -  $get_automatics['total_amount'];

						/**
						$Db_user_freeze = D('User_freeze');
						$user_freeze_data['info']       = "【自动】投标 [{$now_order['did']}] 冻结资金";
						$user_freeze_data['type']       = 7; // 7 投标成功资金冻结
						$user_freeze_data['freezetime'] = time();
						$user_freeze_data['uid']        = $get_automatics['uid'];
						$user_freeze_data['freezemoney']= $get_automatics['total_amount'];
						$user_freeze_data['status']     = 0;
						$user_freeze_data['typeofs']    = 1;
						$Db_user_freeze->add($user_freeze_data);
						 */

						$Db_user_money_list->add($money_list_data);
						//

					}else if($surplus_meoney > 0){ //说明 剩余资金额 = 投标总额 - 借款总额，已经投资金额=借款总额 ,也是满标
						$investmentdata['Amount']   = $now_order['Amount'];
						$investmentdata['Amountdx'] = $this->number2Chinese($now_order['Amount']); //投资中文数字
						//每期利息收益 = 年利率 * 投资额 / 360 * 还款周期
						$investmentdata['nsy'] =number_format($now_order['Rate'] * $now_order['Amount'] / 360 * $now_order['LoanCycle'],2);; //每期利息收益
						$investmentdata['status']   = 1; //投资中
						$borrows_save_data['status'] = 1; //借款还在集标中
						$automatics_save_data['surplus_meoney'] =$surplus_meoney; //投资剩余资金额
						$automatics_save_data['has_meoney']     = $now_order['Amount']; //已经投资金额
						//贷款人增加贷款总额
						$stay_total = $now_order['Amount'] + $now_order['zlx'] + $now_order['zglf']; //待还总额 = 本次借款总额+本次总利息 + 管理费
						$Db_pledges->where(array('uid'=>$now_order['borrowstatus']))->setInc('stay_total',$stay_total);
						//有剩余部分的余额需要把剩余的投资资金解冻出来，增加到用户now金额
						$Db_user->where('`uid`='.$get_automatics['uid'])->setInc('now_money',$surplus_meoney);
						$borrows_save_data['needAmount'] = $now_order['needAmount'] - $now_order['Amount'];//先减去还需要投资金额
						if(!empty($pledgesresult)){
							$Db_pledges->where('`uid`='.$get_automatics['uid'])->setInc('lend_total',$now_order['Amount']); //增加个人借出总额,
						}else{
							$pledges_add['uid'] =$get_automatics['uid'];
							$pledges_add['lend_total'] = $now_order['Amount'];
							$Db_pledges->add($pledges_add);
						}

						// 投标人的资金记录，结金额记录 【投标xxxx 冻结资金】

						$Db_user_money_list = M('User_money_list');

						$money_list_data['desc']       = "【自动】投标 [{$now_order['did']}] 借出扣款";
						$money_list_data['type']       = 22; //借出扣款
						$money_list_data['typeofs']    = 1;
						$money_list_data['time']       = time();
						$money_list_data['uid']        = $get_automatics['uid'];
						$money_list_data['money']      = $get_automatics['total_amount'];
						$money_list_data['now_money']  = $user_now_money -  $now_order['Amount'];

						/**
						$Db_user_freeze = D('User_freeze');
						$user_freeze_data['info']       = "【自动】投标 [{$now_order['did']}] 冻结资金";
						$user_freeze_data['type']       = 7; // 7 投标成功资金冻结
						$user_freeze_data['freezetime'] = time();
						$user_freeze_data['uid']        = $get_automatics['uid'];
						$user_freeze_data['freezemoney']= $now_order['Amount'];
						$user_freeze_data['status']     = 0;
						$user_freeze_data['typeofs']    = 1;
						$Db_user_freeze->add($user_freeze_data);
						*/
						$Db_user_money_list->add($money_list_data);


					}

					$borrows_save_data['investor_tatol'] = $now_order['investor_tatol'] + 1;	//总投资数
					$borrows_save_data['inves_uids'] =  $now_order['inves_uids'] ? $now_order['inves_uids'].','.$get_automatics['uid'] : $get_automatics['uid'];//投资人uid以逗号(,)分隔 [一个人多次投标]
					$borrows_save_data['bid'] = $now_order['bid'];
					//投资进度(投资总额-需要投资金额/投资总额)
					$borrows_save_data['invesing'] = intval((($now_order['Amount'] - $borrows_save_data['needAmount']) / $now_order['Amount']) * 100);


					$automatics_save_data['uid'] = $get_automatics['uid'];
					$automatics_save_data['aid'] = $get_automatics['aid'];
					$automatics_save_data['invalid'] = 0; //自动投资成功，设置该自动设置为失效
					$automatics_save_data['LoanCycle'] = $now_order['LoanCycle']; //投资期数
					$automatics_save_data['autoTime'] = time(); //自动投标时间'
/*
					echo "自动投标成功之后的设置<br/>";
					dump($automatics_save_data);
					echo "剩余资金：".$surplus_meoney." -- 真正剩余：".$automatics_save_data['surplus_meoney']."<br/>";
					*/
					$Db_automatic->data($automatics_save_data)->save();// 更新自动投标的信息
					$Db_borrows->data($borrows_save_data)->save(); //更新借款信息
					$Db_investment->data($investmentdata)->add(); //添加投资人信息
//					file_put_contents('auto_borrows_save_data.log',print_r($borrows_save_data,true));
//					file_put_contents('auto_investmentdata.log',print_r($investmentdata,true));
//					file_put_contents('auto_automatics_save_data.log',print_r($automatics_save_data,true));
					/** 【自动投标】 结束*/
					/**
					echo "更新借款信息<br/>";
					dump($borrows_save_data);
					echo "添加投资人信息<br/>";
					dump($investmentdata);
					 */
				}

				//die;

				/**
				 * 【自动投标和回款投标】 结束
				 */
			}


			$this->frame_submit_tips(1,'审核成功！');
		}else{

			$this->frame_submit_tips(0,'审核失败！');
		}


	}

	public function show(){
		$bid = isset($_GET['bid']) ? intval($_GET['bid']) : 0;
		if($bid >0){
			$Db_borrows = D('Borrows');
			$condition['bid'] = intval($_GET['bid']);
			$now_order = $Db_borrows->field(true)->where($condition)->find();
			if(empty($now_order)){
				$this->frame_error_tips('数据库中没有查询到该内容！',3);
			}

			$this->assign('now_order',$now_order);
		}else{
			$this->frame_error_tips('操作失败！',3);
		}
		$this->display();
	}

	//还款记录：
	public function repaymentlog(){
		$bid = isset($_GET['bid']) ? intval($_GET['bid']) : 0;
		if($bid >0){
			//$Db_borrows = D('Borrows');
			$Db_payment_history = D('Payment_history');
			$condition['bid'] = $bid;
			$count_info = $Db_payment_history->where($condition)->count();

			import('@.ORG.system_page');
			$p = new Page($count_info, 10);
			$now_order = $Db_payment_history->field(true)->where($condition)->limit($p->firstRow . ',' . $p->listRows)->select();

			if(empty($now_order)){
				$this->frame_error_tips('数据库中没有查询到该内容！',3);
			}
			/*
			$now_order = $Db_borrows->field(true)->where($condition)->find();
			if(empty($now_order)){
				$this->frame_error_tips('数据库中没有查询到该内容！',3);
			}
			 */
			$pagebar = $p->show();
			$this->assign('pagebar', $pagebar);

			$this->assign('now_order',$now_order);
		}else{
			$this->frame_error_tips('操作失败！',3);
		}
		$this->display();
	}

	//违约记录
	public function defaultslog(){

		$bid = isset($_GET['bid']) ? intval($_GET['bid']) : 0;
		if($bid >0){
			//$Db_borrows = D('Borrows');
			$Db_breachs = D('Breachs');
			$condition['bid'] = $bid;
			$count_info = $Db_breachs->where($condition)->count();

			import('@.ORG.system_page');
			$p = new Page($count_info, 10);
			$now_order = $Db_breachs->field(true)->where($condition)->limit($p->firstRow . ',' . $p->listRows)->select();

			if(empty($now_order)){
				$this->frame_error_tips('数据库中没有查询到该内容！',3);
			}

			$pagebar = $p->show();
			$this->assign('pagebar', $pagebar);

			$this->assign('now_order',$now_order);
		}else{
			$this->frame_error_tips('操作失败！',3);
		}
		$this->display();
	}

	public function del(){
		$bid = isset($_POST['bid']) ? intval($_POST['bid']) : 0;
		if($bid>0){
			$Db_borrows = D('Borrows');
			$borrows_pids = $Db_borrows->where(array('bid'=>$bid))->getField('pids');
			$pledge_id = explode(',',$borrows_pids);
			$Db_pledge_domain = D('Pledge_domain');
			foreach($pledge_id as $val){
				$pledge_save['rz_status'] = 0;
				$Db_pledge_domain->where('`pid`='.$val)->data($pledge_save)->save();
			}
			/*if($Db_borrows->where(array('bid'=>$bid))->delete()){
				$this->success('删除成功！');
				exit();
			}else{
				$this->error('删除失败！请重试~');
				exit();
			}*/
			exit();
		}
		$this->error('操作失败！请重试~');
	}

	/**
	 * 阿利伯数字转为中文汉字数字
	 * @param $num
	 * @param int $m
	 * @return string
	 *
	 */
	function number2Chinese($num, $m = 0) {
		switch($m) {
			case 0:
				$CNum = array(
					array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"),
					array('','拾','佰','仟'),
					//array('','萬','億','萬億')
					array('','万','亿','万亿')
				);
				break;
			default:
				$CNum = array(
					array('零','一','二','三','四','五','六','七','八','九'),
					array('','十','百','千'),
					array('','万','亿','万亿')
				);
				break;
		}
		if (is_integer($num)) {
			$int = (string)$num;
		} else if (is_numeric($num)) {
			$num = explode('.', (string)floatval($num));
			$int = $num[0];
			$fl  = isset($num[1]) ? $num[1] : FALSE;
		}

		// 长度
		$len = strlen($int);
		$chinese = array();
		$str = strrev($int);

		for($i = 0; $i<$len; $i+=4 ) {
			$s = array(0=>$str[$i], 1=>$str[$i+1], 2=>$str[$i+2], 3=>$str[$i+3]);

			$j = '';
			// 千位
			if ($s[3] !== '') {
				$s[3] = (int) $s[3];
				if ($s[3] !== 0) {
					$j .= $CNum[0][$s[3]].$CNum[1][3];
				} else {
					if ($s[2] != 0 || $s[1] != 0 || $s[0]!=0) {
						$j .= $CNum[0][0];
					}
				}
			}
			// 百位
			if ($s[2] !== '') {
				$s[2] = (int) $s[2];
				if ($s[2] !== 0) {
					$j .= $CNum[0][$s[2]].$CNum[1][2];
				} else {
					if ($s[3]!=0 && ($s[1] != 0 || $s[0]!=0) ) {
						$j .= $CNum[0][0];
					}
				}
			}
			// 十位
			if ($s[1] !== '') {
				$s[1] = (int) $s[1];
				if ($s[1] !== 0) {
					$j .= $CNum[0][$s[1]].$CNum[1][1];
				} else {
					if ($s[0]!=0 && $s[2] != 0) {
						$j .= $CNum[0][$s[1]];
					}
				}
			}
			// 个位
			if ($s[0] !== '') {
				$s[0] = (int) $s[0];
				if ($s[0] !== 0) {
					$j .= $CNum[0][$s[0]].$CNum[1][0];
				} else {

					// $j .= $CNum[0][0];

				}
			}

			$j.=$CNum[2][$i/4];
			array_unshift($chinese, $j);
		}

		$chs = implode('', $chinese);

		if ($fl) {
			$chs .= '点';
			for($i=0,$j=strlen($fl); $i<$j; $i++) {
				$t = (int)$fl[$i];
				$chs.= $str[0][$t];
			}
		}

		return $chs;
	}

	/**
	 * 冒泡获取最低的利率
	 * @param $rate array
	 * $rate = array(5, 15, 11, 4, 12);
		$s = getRateMin($rate);
		print_r($s);
	 */
  public function getRateMin($rate){
	  $count = count($rate);
	  if($count <= 0){
		  return false;
	  }
	  for($i=0 ; $i < $count;$i++ ){
		  for($j =$count -1; $j>$i;$j--){
			if($rate[$j] < $rate[$j-1]){
				$tmp       = $rate[$j];
				$rate[$j]  = $rate[$j-1];
				$rate[$j-1]= $tmp;
			}
		  }
	  }
	  return $rate;
  }

}